package com.iams.manage.validator;

import com.iams.common.utils.DateUtils;
import com.iams.common.utils.SecurityUtils;
import com.iams.manage.domain.BorrowRecord;
import com.iams.manage.mapper.ArchiveMapper;
import com.iams.manage.mapper.BorrowRecordMapper;
import com.iams.manage.service.IArchiveService;
import com.iams.manage.service.IBorrowRecordService;
import com.iams.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 借阅记录验证器
 *
 * @author LiuTao
 * @date 2025-03-28
 */
@Component
public class BorrowRecordValidator {

    // 使用Mapper，而非service，避免循环依赖
    @Autowired
    private ArchiveMapper archiveMapper;
    @Autowired
    private BorrowRecordMapper borrowRecordMapper;

    public void validate(BorrowRecord borrowRecord) {

        // 检查用户信息，利用securityUtils获取当前登录用户信息，匹配前端传来的信息
        if(!borrowRecord.getUserId().equals(SecurityUtils.getLoginUser().getUserId())||!borrowRecord.getUserName().equals(SecurityUtils.getLoginUser().getUser().getUserName()))
        {
            throw new RuntimeException("请正确输入您自己的用户信息");
        }

        // 检查是否已经被借阅，通过（档案ID、用户ID、借阅状态）三个条件
        // 已检查用户信息，直接使用用户ID
        // 利用若依生成的mapper接口，查询借阅记录列表，带有条件查询
        // 新增BorrowRecord构造函数， 传入ArchiveID、UserID
        List<BorrowRecord> list = borrowRecordMapper.selectBorrowRecordList(new BorrowRecord(borrowRecord.getArchiveId(), borrowRecord.getUserId()));
        for (BorrowRecord userborrowRecord : list) {
            // 检查是否存在借阅记录且状态为已批准
            if (userborrowRecord.getStatus().equals("approved")) {
                throw new RuntimeException("您已经借阅过该档案，请勿重复借阅");
            }
            if (userborrowRecord.getStatus().equals("pending")) {
                throw new RuntimeException("您已提交借阅申请，请等待审批");
            }

        }

        // 检查档案是否存在
        if(archiveMapper.selectArchiveById(borrowRecord.getArchiveId())==null)
        {
            throw new RuntimeException("借阅的档案不存在");
        }
        // 检查借阅时间是否合法
        Date today = DateUtils.getNowDate();
        Date startDate = borrowRecord.getStartDate();
        Date endDate = borrowRecord.getEndDate();

        today = DateUtils.truncate(today, Calendar.DATE);
        startDate = DateUtils.truncate(startDate, Calendar.DATE);


        // 允许今天：当且仅当 startDate < today 时报错
        if (startDate.before(today)) {
            throw new RuntimeException("借阅日期不能早于当前日期");
        }

        // 结束日期必须 >= 开始日期
        if (endDate.before(startDate)) {
            throw new RuntimeException("归还日期不能早于借阅日期");
        }
    }
}
